package com.jvtd.zego;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.res.Configuration;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.RelativeLayout;

import com.zego.zegoliveroom.ZegoLiveRoom;
import com.zego.zegoliveroom.callback.IZegoLivePlayerCallback;
import com.zego.zegoliveroom.callback.IZegoLoginCompletionCallback;
import com.zego.zegoliveroom.callback.IZegoRoomCallback;
import com.zego.zegoliveroom.callback.im.IZegoIMCallback;
import com.zego.zegoliveroom.constants.ZegoConstants;
import com.zego.zegoliveroom.constants.ZegoVideoViewMode;
import com.zego.zegoliveroom.entity.ZegoStreamInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class JvtdLiveView extends RelativeLayout {
    protected Context mContext;
    protected boolean mHostHasBeenCalled = false;
    protected ZegoLiveRoom mZegoLiveRoom = null;
    protected Activity mActivity;
    protected String mRoomID = null;
    protected String mStreamID = null;
    protected PhoneStateListener mPhoneStateListener = null;//电话状态监听
    protected TextureView mLiveView;//直播界面
    protected View mRootView;

    public JvtdLiveView(Context context) {
        this(context, null);
    }

    public JvtdLiveView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public JvtdLiveView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    //初始化设置来电监听
    private void initView(Context context) {
        mContext = context;
        mRootView = LayoutInflater.from(context).inflate(R.layout.jvtd_live_view_layout, this);
        mLiveView = mRootView.findViewById(R.id.jvtd_live_texture_view);
    }

    //设置liveroom
    public JvtdLiveView initLiveRoom(Activity activity, ZegoLiveRoom zegoLiveRoom) {
        this.mZegoLiveRoom = zegoLiveRoom;
        this.mActivity = activity;
        initPhoneCallingListener();
        return this;
    }

    //登录房间
    public JvtdLiveView loginRoom(String roomID, IZegoLoginCompletionCallback callback) {
        this.mRoomID = roomID;
        mZegoLiveRoom.loginRoom(roomID, ZegoConstants.RoomRole.Audience, new IZegoLoginCompletionCallback() {
            @Override
            public void onLoginCompletion(int i, ZegoStreamInfo[] zegoStreamInfos) {
                callback.onLoginCompletion(i, zegoStreamInfos);
                if (i == 0)
                    handleAudienceLoginRoomSuccess(zegoStreamInfos);
            }
        });
        return this;
    }

    //直播播放回调
    public JvtdLiveView setLivePlayerCallback(IZegoLivePlayerCallback callback) {
        mZegoLiveRoom.setZegoLivePlayerCallback(callback);
        return this;
    }

    //设置直播聊天室回调
    public JvtdLiveView setIMCallback(IZegoIMCallback callback) {
        mZegoLiveRoom.setZegoIMCallback(callback);
        return this;
    }

    //房间状态回调
    public JvtdLiveView setRoomCallback(IZegoRoomCallback callback) {
        mZegoLiveRoom.setZegoRoomCallback(new IZegoRoomCallback() {
            @Override
            public void onKickOut(int i, String s) {
                callback.onKickOut(i, s);
            }

            @Override
            public void onDisconnect(int i, String s) {
                callback.onDisconnect(i, s);
            }

            @Override
            public void onReconnect(int i, String s) {
                callback.onReconnect(i, s);
            }

            @Override
            public void onTempBroken(int i, String s) {
                callback.onTempBroken(i, s);
            }

            @Override
            public void onStreamUpdated(int i, ZegoStreamInfo[] zegoStreamInfos, String s) {
                callback.onStreamUpdated(i, zegoStreamInfos, s);
                if (zegoStreamInfos != null && zegoStreamInfos.length > 0) {
                    switch (i) {
                        case ZegoConstants.StreamUpdateType.Added:
                            handleStreamAdded(zegoStreamInfos, s);
                            break;
                        case ZegoConstants.StreamUpdateType.Deleted:
                            handleStreamDeleted(zegoStreamInfos, s);
                            break;
                    }
                }
            }

            @Override
            public void onStreamExtraInfoUpdated(ZegoStreamInfo[] zegoStreamInfos, String s) {
                callback.onStreamExtraInfoUpdated(zegoStreamInfos, s);
            }

            @Override
            public void onRecvCustomCommand(String s, String s1, String s2, String s3) {
                callback.onRecvCustomCommand(s, s1, s2, s3);
            }
        });
        return this;
    }

    /**
     * 电话状态监听.
     */
    protected void initPhoneCallingListener() {
        mPhoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                switch (state) {
                    case TelephonyManager.CALL_STATE_IDLE:
                        if (mHostHasBeenCalled) {
                            mHostHasBeenCalled = false;
                            //收到PhoneStateManager回调的 TelephonyManager.CALL_STATE_IDLE 事件时，可能系统的设备还未释放完毕，需要延迟2s再调用mZegoLiveRoom.resumeModule(ZegoConstants.ModuleType.AUDIO)
                            mActivity.getWindow().getDecorView().postDelayed(() -> mZegoLiveRoom.resumeModule(ZegoConstants.ModuleType.AUDIO), 2000);
                        }

                        break;
                    case TelephonyManager.CALL_STATE_RINGING:
                        mHostHasBeenCalled = true;
                        // 来电，暂停音频模块
                        mZegoLiveRoom.pauseModule(ZegoConstants.ModuleType.AUDIO);
                        break;

                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        break;
                }
            }
        };

        TelephonyManager tm = (TelephonyManager) mActivity.getSystemService(Service.TELEPHONY_SERVICE);
        if (tm != null) {
            tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }
    }

    //销毁
    public void onDestroy() {
        // 注销电话监听
        TelephonyManager tm = (TelephonyManager) mActivity.getSystemService(Service.TELEPHONY_SERVICE);
        if (tm != null) {
            tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
        }
        mPhoneStateListener = null;
    }

    //获取空闲的View用于播放或者发布.
    protected TextureView getLiveView() {
        return mLiveView;
    }

    public void logout() {
        mZegoLiveRoom.enableSpeaker(true);
        // 清空回调, 避免内存泄漏
        mZegoLiveRoom.setZegoLivePublisherCallback(null);
        mZegoLiveRoom.setZegoLivePlayerCallback(null);
        mZegoLiveRoom.setZegoRoomCallback(null);
        mZegoLiveRoom.setZegoIMCallback(null);
        // 退出房间
        mZegoLiveRoom.logoutRoom();
    }

    /**
     * 开始播放流.
     */
    public void startPlay(String streamID) {
        if (TextUtils.isEmpty(streamID)) {
            return;
        }
        // 播放
        mStreamID = streamID;
        mZegoLiveRoom.startPlayingStream(streamID, getLiveView());
        mZegoLiveRoom.setViewMode(ZegoVideoViewMode.ScaleAspectFit, streamID);
    }

    public void stopPlay(String streamID) {
        if (!TextUtils.isEmpty(streamID)) {
            mZegoLiveRoom.stopPlayingStream(streamID);
        }
        mStreamID = null;
    }

    /**
     * 观众登录房间成功.
     */
    protected void handleAudienceLoginRoomSuccess(ZegoStreamInfo[] zegoStreamInfos) {
        // 播放房间的流
        if (zegoStreamInfos != null && zegoStreamInfos.length > 0) {
            for (ZegoStreamInfo zegoStreamInfo : zegoStreamInfos) {
                String streamId = zegoStreamInfo.streamID;
                startPlay(streamId);
            }
        }
    }

    /**
     * 房间内用户创建流.
     */
    protected void handleStreamAdded(final ZegoStreamInfo[] listStream, final String roomID) {
        if (listStream != null && listStream.length > 0) {
            for (ZegoStreamInfo aListStream : listStream) {
                startPlay(aListStream.streamID);
            }
        }
    }

    /**
     * 房间内用户删除流.
     */
    protected void handleStreamDeleted(final ZegoStreamInfo[] listStream, final String roomID) {
        if (listStream != null && listStream.length > 0) {
            for (ZegoStreamInfo aListStream : listStream) {
                stopPlay(aListStream.streamID);
            }
        }
    }

    public void handleConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        int currentOrientation =mActivity.getWindowManager().getDefaultDisplay().getRotation();
        mZegoLiveRoom.setViewRotation(currentOrientation, mStreamID);
    }
}
